#pragma once
#include <iostream>
#include <functional>
#include "Log.hpp"
#include <unistd.h>

typedef std::function<void(int)> func_t;

namespace wyl
{
    void IOServer(int sock)
    {
        char buff[1024] = {0};
        for (;;)
        {
            // 读数据
            int n = read(sock, buff, sizeof buff - 1);
            if (n > 0)
            {
                buff[n] = 0;
                std::string message = "[Server Echo] :";
                message += buff;
                std::cout << "clinet : " << buff << std::endl;
                write(sock, message.c_str(), message.size()); // 写数据
            }
            else if (n == 0)
            {
                logMessage(NORMAL, "client quit... me too");
                break;
            }
            else
            {
                logMessage(ERROR, "read failed..... sock : %d", sock);
                break;
            }
        }
        close(sock);
    }

    class Task
    {
    public:
        Task() {}
        Task(int sock, func_t func) : _sock(sock), _func(func) {}

        void operator()()
        {
            _func(_sock);
        }

    public:
        int _sock;
        func_t _func;
    };
}